<template>
  <div class="fixed-container">
    <div style="padding-bottom: 10px; display: flex;justify-content: space-between;">
      <router-link to="/main/xingzheng/gudingzichan" class="btn-link"
        ><button>返回</button></router-link
      >
      <div class="action-buttons">
        <button @click="addItem" v-if="!isView" class="add-btn">
          新增明细
        </button>
        <button @click="saveData" v-if="!isView" class="save-btn">保存</button>
        <button @click="goToList" class="back-btn">列表</button>
        <button @click="printPdf" class="print-btn">打印PDF</button>
      </div>
    </div>
    <div id="form" style="background-color: #fff; padding: 20px">
      <h2 style="text-align: center">支付证明单</h2>
      <div style="width: 100%; display: flex">
        <span>
          <label>部门代号：</label>
          <input
            class="underline-input1"
            v-model="formData.departmentCode"
            :disabled="isView"
          />
        </span>
      </div>
      <div
        style="
          width: 100%;
          display: flex;
          justify-content: space-between;
          margin: 5px 0px;
        "
      >
        <span>
          <label>部门名称：</label>
          <input
            class="underline-input1"
            v-model="formData.departmentName"
            :disabled="isView"
          />
        </span>
        <span>
          <label>日期：</label>
          <input
            class="underline-input1"
            v-model="formData.date.year"
            style="width: 40px"
            :disabled="isView"
          />
          年
          <input
            class="underline-input1"
            v-model="formData.date.month"
            style="width: 40px"
            :disabled="isView"
          />
          月
          <input
            class="underline-input1"
            v-model="formData.date.day"
            style="width: 40px"
            :disabled="isView"
          />
          日
        </span>
      </div>
      <table border="1" style="width: 100%; text-align: center">
        <thead>
          <tr>
            <th rowspan="2">品名</th>
            <th rowspan="2">数量</th>
            <th rowspan="2">单价（元）</th>
            <th colspan="14">金额</th>
            <th rowspan="2">用途及说明</th>
          </tr>
          <tr>
            <th class="digit-cell">千</th>
            <th class="digit-cell">百</th>
            <th class="digit-cell">十</th>
            <th class="digit-cell">亿</th>
            <th class="digit-cell">千</th>
            <th class="digit-cell">百</th>
            <th class="digit-cell">十</th>
            <th class="digit-cell">万</th>
            <th class="digit-cell">千</th>
            <th class="digit-cell">百</th>
            <th class="digit-cell">十</th>
            <th class="digit-cell">元</th>
            <th class="digit-cell">角</th>
            <th class="digit-cell">分</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in itemList" :key="index">
            <td><input v-model="item.productName" :disabled="isView" /></td>
            <td>
              <input
                v-model="item.quantity"
                type="number"
                min="0"
                :disabled="isView"
                @input="calculateAmount(index)"
              />
            </td>
            <td>
              <input
                v-model="item.unitPrice"
                type="number"
                min="0"
                :disabled="isView"
                @input="calculateAmount(index)"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[0]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[1]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[2]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[3]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[4]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[5]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[6]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[7]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[8]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[9]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[10]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[11]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[12]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td>
              <input
                class="amount-digits"
                v-model="item.amountDigits[13]"
                type="number"
                min="0"
                :disabled="true"
              />
            </td>
            <td><input v-model="item.purpose" :disabled="isView" /></td>
          </tr>
          <tr>
            <td>合计金额(大写)：</td>
            <td colspan="17" style="white-space: nowrap">
              <div class="amount-words-container">
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.trillion"
                    :disabled="isView"
                  />
                  兆
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.hundredBillion"
                    :disabled="isView"
                  />
                  仟
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.tenBillion"
                    :disabled="isView"
                  />
                  佰
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.billion"
                    :disabled="isView"
                  />
                  拾
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.currency"
                    :disabled="isView"
                  />
                  亿
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.hundred"
                    :disabled="isView"
                  />
                  佰
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.ten"
                    :disabled="isView"
                  />
                  拾
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.thousand"
                    :disabled="isView"
                  />
                  万
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.hundredThousand"
                    :disabled="isView"
                  />
                  仟
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.tenThousand"
                    :disabled="isView"
                  />
                  佰
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.thousandUnit"
                    :disabled="isView"
                  />
                  拾
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.hundredUnit"
                    :disabled="isView"
                  />
                  元
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.tenUnit"
                    :disabled="isView"
                  />
                  角
                </div>
                <div class="amount-word-item">
                  <input
                    class="amount-in-words"
                    v-model="formData.totalAmountInWords.unit"
                    :disabled="isView"
                  />
                  分
                </div>
                <div class="amount-digit-container">
                  <label>￥</label>
                  <input
                    style="width: 100%"
                    v-model="formData.totalAmountInDigits"
                    type="number"
                    min="0"
                    :disabled="isView"
                  />
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- 其他部分保持不变 -->
    </div>
  </div>
</template>

<script>
import axios from "axios";
import html2pdf from "html2pdf.js";
import { savePaymentProof, getPaymentProofDetail } from "@/api/paymentProof";

export default {
  data() {
    return {
      pageType: "add", // add, edit, view
      formData: {
        departmentCode: "",
        departmentName: "",
        date: {
          year: "",
          month: "",
          day: "",
        },
        totalAmountInWords: {
          currency: "",
          hundred: "",
          ten: "",
          thousand: "",
          hundredThousand: "",
          tenThousand: "",
          thousandUnit: "",
          hundredUnit: "",
          tenUnit: "",
          unit: "",
          trillion: "",
          hundredBillion: "",
          tenBillion: "",
          billion: "",
        },
        totalAmountInDigits: 0,
        approver: "",
        reviewer: "",
        departmentApprover: "",
        applicant: "",
        reviewer2: "",
        formMaker: "",
        cashier: "",
        recipient: "",
      },
      itemList: [
        {
          productName: "",
          quantity: 0,
          unitPrice: 0,
          amountDigits: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          purpose: "",
        },
      ],
    };
  },
  computed: {
    isView() {
      return this.pageType === "view";
    },
  },
  created() {
    this.initPageData();
  },
  methods: {
    async initPageData() {
      const { id, type } = this.$route.query;
      if (type) {
        this.pageType = type;
      }
      if (id) {
        try {
          const response = await getPaymentProofDetail(id);
          console.log("详情数据：", response); // 添加日志
          const detail = response.data;
          // 填充主表数据
          this.formData = {
            departmentCode: detail.departmentCode || "",
            departmentName: detail.departmentName || "",
            date: {
              year: detail.statisticsYear || "",
              month: detail.statisticsMonth || "",
              day: detail.statisticsDay || "",
            },
            totalAmountInWords: detail.totalAmountWords
              ? JSON.parse(detail.totalAmountWords)
              : {
                  currency: "",
                  hundred: "",
                  ten: "",
                  thousand: "",
                  hundredThousand: "",
                  tenThousand: "",
                  thousandUnit: "",
                  hundredUnit: "",
                  tenUnit: "",
                  unit: "",
                  trillion: "",
                  hundredBillion: "",
                  tenBillion: "",
                  billion: "",
                },
            totalAmountInDigits: detail.totalAmount || 0,
            approver: detail.approver || "",
            reviewer: detail.reviewer || "",
            departmentApprover: detail.departmentApprover || "",
            applicant: detail.applicant || "",
            reviewer2: detail.reviewer2 || "",
            formMaker: detail.formMaker || "",
            cashier: detail.cashier || "",
            recipient: detail.recipient || "",
          };
          // 填充明细数据
          if (detail.itemList && detail.itemList.length > 0) {
            this.itemList = detail.itemList.map((item) => ({
              productName: item.productName || "",
              quantity: item.quantity || 0,
              unitPrice: item.unitPrice || 0,
              amountDigits: this.convertAmountToDigits(item.amount),
              purpose: item.purpose || "",
            }));
          } else {
            this.itemList = [
              {
                productName: "",
                quantity: 0,
                unitPrice: 0,
                amountDigits: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                purpose: "",
              },
            ];
          }

          // 更新总金额
          this.updateTotalAmount();
        } catch (error) {
          console.error("获取详情错误：", error); // 添加错误日志
          this.$message.error("获取详情失败：" + error.message);
        }
      }
    },
    convertAmountToDigits(amount) {
      if (!amount) return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

      // 将金额转为字符串，保留两位小数
      const amountStr = amount.toFixed(2).replace(".", "");

      // 如果金额超过14位数（不含小数点后两位），只保留最后14位
      if (amountStr.length > 14) {
        const digits = amountStr.slice(-14).split("").map(Number);
        return digits;
      } else {
        // 正常处理14位以内的数字
        const digits = amountStr.padStart(14, "0").split("").map(Number);
        return digits;
      }
    },
    calculateAmount(index) {
      // 获取数量和单价
      const quantity = parseFloat(this.itemList[index].quantity) || 0;
      const unitPrice = parseFloat(this.itemList[index].unitPrice) || 0;

      // 计算金额
      const amount = quantity * unitPrice;

      // 将金额转换为数字数组
      this.itemList[index].amountDigits = this.convertAmountToDigits(amount);

      // 更新总金额
      this.updateTotalAmount();
    },
    updateTotalAmount() {
      // 计算所有项目的总金额
      let totalAmount = 0;
      for (const item of this.itemList) {
        const amountStr = item.amountDigits.join("");
        const amount =
          parseFloat(amountStr.slice(0, -2) + "." + amountStr.slice(-2)) || 0;
        totalAmount += amount;
      }

      // 更新总金额
      this.formData.totalAmountInDigits = totalAmount.toFixed(2);

      // 转换为中文大写金额
      this.convertToChineseAmount(totalAmount);
    },
    convertToChineseAmount(amount) {
      // 数字对应的中文
      const chineseNums = [
        "零",
        "壹",
        "贰",
        "叁",
        "肆",
        "伍",
        "陆",
        "柒",
        "捌",
        "玖",
      ];

      // 处理金额为0的情况
      if (amount === 0) {
        this.formData.totalAmountInWords = {
          currency: "",
          hundred: "",
          ten: "",
          thousand: "",
          hundredThousand: "",
          tenThousand: "",
          thousandUnit: "",
          hundredUnit: "",
          tenUnit: "",
          unit: "",
          trillion: "",
          hundredBillion: "",
          tenBillion: "",
          billion: "",
        };
        return;
      }

      // 将金额转为字符串，保留两位小数
      const amountStr = amount.toFixed(2);

      // 分离整数部分和小数部分
      const parts = amountStr.split(".");
      const integerPart = parts[0];
      const decimalPart = parts[1];

      // 处理整数部分
      const intLength = integerPart.length;

      // 初始化中文金额对象
      const chineseAmount = {
        currency: "",
        hundred: "",
        ten: "",
        thousand: "",
        hundredThousand: "",
        tenThousand: "",
        thousandUnit: "",
        hundredUnit: "",
        tenUnit: "",
        unit: "",
        trillion: "",
        hundredBillion: "",
        tenBillion: "",
        billion: "",
      };

      // 处理整数部分
      for (let i = 0; i < intLength; i++) {
        const digit = parseInt(integerPart[i]);
        const position = intLength - i - 1;

        if (digit === 0) continue; // 跳过零

        this.setDigitAtPosition(chineseAmount, digit, position);
      }

      // 处理小数部分（角分）
      if (decimalPart) {
        const jiao = parseInt(decimalPart[0]);
        const fen = parseInt(decimalPart[1]);

        if (jiao > 0) {
          chineseAmount.tenUnit = chineseNums[jiao];
        }

        if (fen > 0) {
          chineseAmount.unit = chineseNums[fen];
        }
      }

      // 更新表单中的中文金额
      this.formData.totalAmountInWords = chineseAmount;
    },

    // 辅助方法：将数字设置到对应位置
    setDigitAtPosition(chineseAmount, digit, position) {
      const chineseNums = [
        "零",
        "壹",
        "贰",
        "叁",
        "肆",
        "伍",
        "陆",
        "柒",
        "捌",
        "玖",
      ];

      switch (position) {
        case 0: // 个位
          chineseAmount.hundredUnit = chineseNums[digit];
          break;
        case 1: // 十位
          chineseAmount.thousandUnit = chineseNums[digit];
          break;
        case 2: // 百位
          chineseAmount.tenThousand = chineseNums[digit];
          break;
        case 3: // 千位
          chineseAmount.hundredThousand = chineseNums[digit];
          break;
        case 4: // 万位
          chineseAmount.thousand = chineseNums[digit];
          break;
        case 5: // 十万位
          chineseAmount.ten = chineseNums[digit];
          break;
        case 6: // 百万位
          chineseAmount.hundred = chineseNums[digit];
          break;
        case 7: // 千万位
          chineseAmount.currency = chineseNums[digit];
          break;
        case 8: // 亿位
          chineseAmount.billion = chineseNums[digit];
          break;
        case 9: // 十亿位
          chineseAmount.tenBillion = chineseNums[digit];
          break;
        case 10: // 百亿位
          chineseAmount.hundredBillion = chineseNums[digit];
          break;
        case 11: // 千亿位
          chineseAmount.trillion = chineseNums[digit];
          break;
      }
    },
    addItem() {
      this.itemList.push({
        productName: "",
        quantity: 0,
        unitPrice: 0,
        amountDigits: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        purpose: "",
      });
    },
    goToList() {
      this.$router.push("/main/xingzheng/zhifuzmd/zhifuzmdList");
    },
    async saveData() {
      try {
        // 验证表单必填项
        if (!this.formData.departmentCode) {
          this.$message.error("请填写部门代号");
          return;
        }
        if (!this.formData.departmentName) {
          this.$message.error("请填写部门名称");
          return;
        }
        if (
          !this.formData.date.year ||
          !this.formData.date.month ||
          !this.formData.date.day
        ) {
          this.$message.error("请填写完整日期");
          return;
        }

        // 验证明细项
        if (this.itemList.length === 0) {
          this.$message.error("请至少添加一项明细");
          return;
        }

        for (let i = 0; i < this.itemList.length; i++) {
          const item = this.itemList[i];
          if (!item.productName) {
            this.$message.error(`第${i + 1}行请填写品名`);
            return;
          }
          if (!item.quantity || item.quantity <= 0) {
            this.$message.error(`第${i + 1}行请填写有效数量`);
            return;
          }
          if (!item.unitPrice || item.unitPrice <= 0) {
            this.$message.error(`第${i + 1}行请填写有效单价`);
            return;
          }
        }

        const data = {
          id: this.$route.query.id,
          departmentCode: this.formData.departmentCode,
          departmentName: this.formData.departmentName,
          statisticsYear: this.formData.date.year,
          statisticsMonth: this.formData.date.month,
          statisticsDay: this.formData.date.day,
          totalAmount: this.formData.totalAmountInDigits,
          totalAmountWords: JSON.stringify(this.formData.totalAmountInWords),
          approver: this.formData.approver,
          reviewer: this.formData.reviewer,
          departmentApprover: this.formData.departmentApprover,
          applicant: this.formData.applicant,
          reviewer2: this.formData.reviewer2,
          formMaker: this.formData.formMaker,
          cashier: this.formData.cashier,
          recipient: this.formData.recipient,
          itemList: this.itemList.map((item) => {
            const amountStr = item.amountDigits.join("");
            const amount = parseFloat(
              amountStr.slice(0, -2) + "." + amountStr.slice(-2)
            );
            return {
              productName: item.productName,
              quantity: item.quantity,
              unitPrice: item.unitPrice,
              amount: amount,
              purpose: item.purpose,
            };
          }),
        };
        await savePaymentProof(data);
        this.$message.success("保存成功");
        this.$router.push("/main/xingzheng/zhifuzmd/zhifuzmdList");
      } catch (error) {
        this.$message.error("保存失败：" + error.message);
      }
    },
    printPdf() {
      const element = document.getElementById("form");
      const opt = {
        margin: 8, // 适当增加边距
        filename: "支付证明单.pdf",
        image: { type: "", quality: 0.98 },
        html2canvas: { scale: 1.1 }, // 调整缩放比例
        // jsPDF: { unit: "mm", format: "A4", orientation: "portrait" }, // 设置为 A4 格式
        jsPDF: { unit: "mm", format: "A4", orientation: "landscape" }, // 设置为横向A4格式
      };
      html2pdf().from(element).set(opt).save();
    },
  },
};
</script>

<style scoped>
.fixed-container {
  width: 297mm;
  margin: 0 auto;
  min-height: calc(100vh - 40px);
  padding: 20px;
}
table {
  border-collapse: collapse;
  width: 100%;
  /* margin-bottom: 15px; */
}

th,
td {
  border: 1px solid #000;
  padding: 4px 2px;
  font-size: 14px;
}

input {
  box-sizing: border-box;
  border: 0px;
  font-family: "宋体";
  font-size: 14px;
  text-align: center;
  outline: none;
}

.underline-input1 {
  border-bottom: 1px solid black;
  min-width: 120px;
}

.amount-digits {
  width: 90%;
  text-align: center;
  padding: 0;
  margin: 0;
  font-size: 13px;
}

.amount-in-words {
  width: 25px;
  font-size: 13px;
  text-align: center;
}

.amount-words-container {
  display: flex;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.amount-word-item {
  display: flex;
  align-items: center;
  margin-right: 2px;
}

.amount-digit-container {
  margin-left: auto;
  display: flex;
  align-items: center;
}

button {
  margin: 5px;
  padding: 6px 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover {
  background-color: #66b1ff;
}

.btn-link {
  text-decoration: none;
  color: #409eff;
  margin-right: 10px;
}

.print-btn {
  background-color: #67c23a;
}

.print-btn:hover {
  background-color: #85ce61;
}

.action-buttons {
  display: flex;
  justify-content: center;
  /* margin-top: 15px; */
}

.add-btn {
  background-color: #909399;
}

.add-btn:hover {
  background-color: #a6a9ad;
}

.save-btn {
  background-color: #67c23a;
}

.save-btn:hover {
  background-color: #85ce61;
}

.back-btn {
  background-color: #909399;
}

.back-btn:hover {
  background-color: #a6a9ad;
}

/* 打印样式 */
@media print {
  h2 {
    text-align: center;
  }

  #form {
    width: 100%;
    box-sizing: border-box;
  }

  button,
  .action-buttons,
  .btn-link {
    display: none;
  }
}

/* 调整金额列的宽度 */
th:nth-child(n + 4):nth-child(-n + 20) {
  width: 25px;
  padding: 2px 0;
  font-size: 12px;
}

/* 调整用途说明列的宽度 */
th:last-child,
td:last-child {
  width: 150px;
}

/* 调整品名列的宽度 */
th:first-child,
td:first-child {
  width: 120px;
}

/* 调整数量和单价列的宽度 */
th:nth-child(2),
td:nth-child(2),
th:nth-child(3),
td:nth-child(3) {
  width: 60px;
}

/* 调整表格内输入框的样式 */
td input {
  width: 95%;
  height: 24px;
}

/* 调整金额数字输入框的样式 */
td .amount-digits {
  width: 95%;
  height: 20px;
  font-size: 12px;
}

.digit-cell {
  width: 25px !important;
  padding: 2px 0 !important;
  font-size: 12px !important;
}
</style>